/*
 * Copyright (C) 2009 codemobiles.com.
 * http://www.codemobiles.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * author: Chaiyasit Tayabovorn 
 * email: chaiyasit.t@gmail.com
 */
 
package com.codemobiles.droidslator_tattoo.activity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.codemobiles.droidslator_tattoo.AppPreferences;
import com.codemobiles.droidslator_tattoo.R;
import com.codemobiles.droidslator_tattoo.util.MyUtil;
import com.codemobiles.droidslator_tattoo.util.ProgressGUIUpdate;

public class SettingActivity extends Activity implements ProgressGUIUpdate {
  private ImageView imgBanner;
  private ProgressBar mProgress;
  private TextView progressText;
  private Button btnDownload;
  private ArrayAdapter<CharSequence> adapter = null;
  private Spinner plugInSpinner;
  private TextView pluginDesc;
  private float mPercent;
  private String URL_PLUGIN;
  private String fullPluginUrl;
  private String pluginName;
  private URL fetchUrl;
  private long fileSize;
  private InputStream in;
  private File root;
  private final String ROOT_PATH = "/sdcard/";
  private Thread installThread;
  private Handler mHandler = new Handler();
  private final int DOWNLOAD_PROG_ID = 0x01;
  private final int UNZIP_PROG_ID = 0x02;
  private AppPreferences appPref;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.setting);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
    plugInSpinner = (Spinner) findViewById(R.id.plugInSpinner);
    URL_PLUGIN = getString(R.string.url_plugins);
    appPref = AppPreferences.getInstance(this);
    root = Environment.getExternalStorageDirectory();
    adapter = ArrayAdapter.createFromResource(this, R.array.pluginarray, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    plugInSpinner.setAdapter(adapter);

    adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1) {

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        TextView txt = new TextView(this.getContext());

        txt.setTextColor(Color.BLACK);
        txt.setTextSize(10);
        // txt.setBackgroundColor(0xff447744);
        txt.setText(this.getItem(position));
        return txt;
      }
    };

    btnDownload = (Button) findViewById(R.id.download001);
    progressText = (TextView) findViewById(R.id.progressText);
    mProgress = (ProgressBar) findViewById(R.id.progress_bar);
    imgBanner = (ImageView) findViewById(R.id.imgBanner);
    pluginDesc = (TextView) findViewById(R.id.pluginDesc);

    plugInSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {

        switch (position) {
        case 0:
          pluginName = getString(R.string.plugin_lexitron_enth);
          pluginDesc.setText(getString(R.string.plugin_lexitron_enth_desc));
          break;
        case 1:
          pluginName = getString(R.string.plugin_ocr_en);
          pluginDesc.setText(getString(R.string.plugin_ocr_en_desc));
          break;
        }

        updateIntallationDisplay(pluginName);
        fullPluginUrl = URL_PLUGIN + pluginName + getString(R.string.url_plugins_extension);

        Bundle passedData = getIntent().getExtras();
        if (passedData != null && passedData.getBoolean("AUTO_SETUP", false)) {
          fileSize = 0;
          mProgress.setProgress(0);
          btnDownload.setText("Loading");
          btnDownload.setEnabled(false);
          plugInSpinner.setEnabled(false);
          appPref.setValueOf(pluginName, false);
          doInstallatioin();
        }

      }

      @Override
      public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

      }

    });

    btnDownload.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

        fileSize = 0;
        mProgress.setProgress(0);
        btnDownload.setText("Loading");
        btnDownload.setEnabled(false);
        plugInSpinner.setEnabled(false);
        appPref.setValueOf(pluginName, false);
        doInstallatioin();
      }
    });

    imgBanner.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        Uri uri = Uri.parse(getString(R.string.our_website));
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
      }
    });

  }

  private void updateIntallationDisplay(final String pluginKey) {

    if (appPref.getBooleanValueOf(pluginKey)) {
      mProgress.setProgress(100);
      btnDownload.setText("Re-Install");
      progressText.setText("Installed");
    } else {
      mProgress.setProgress(0);
      btnDownload.setText("Install Now");
      progressText.setText("Not Installed Yet");
    }
  }

  /**
   * Call this method to complete Installation processes
   */
  private void doInstallatioin() {
    installThread = new Thread(new Runnable() {
      public void run() {
        downloadInstallationFiles();
        unZipInstallationFiles();
      }
    });
    installThread.start();
  }

  /**
   * Call this method to download required installation files
   */
  private synchronized void downloadInstallationFiles() {

    try {
      fetchUrl = new URL(fullPluginUrl);
      fileSize = fetchUrl.openConnection().getContentLength();
      in = (InputStream) fetchUrl.getContent();
      File f = new File(root, File.separator + pluginName);
      MyUtil.copyInputStream(in, fileSize, f, mHandler, this, DOWNLOAD_PROG_ID);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

  private synchronized void unZipInstallationFiles() {
    ZipFile zipFile;

    try {
      // load zip file
      zipFile = new ZipFile(ROOT_PATH + pluginName);

      // begin unzip process
      Enumeration<?> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        File f = new File(root, File.separator + entry.getName());
        if (entry.isDirectory()) {
          f.mkdirs();
          continue;
        } else {
          f.getParentFile().mkdirs();
          f.createNewFile();
        }

        in = zipFile.getInputStream(entry);
        fileSize = entry.getSize();
        if (!MyUtil.copyInputStream(in, fileSize, f, mHandler, this, UNZIP_PROG_ID)) {
          break;
        }
      }
      zipFile.close();
      new File(ROOT_PATH + pluginName).delete();
      updateProgressGUI(UNZIP_PROG_ID, 100, 0);
    } catch (IOException ioe) {
      System.out.print(ioe.getMessage());
    }
  }

  @Override
  public void updateProgressGUI(int progressID, final float percentDone, final float actualDoneSize) {

    mPercent = percentDone;
    switch (progressID) {
    // download
    case DOWNLOAD_PROG_ID:
      // update progress bar display
      mHandler.post(new Runnable() {
        public void run() {
          mProgress.setProgress((int) mPercent);
          if ((int) (mPercent) == 100) {
            btnDownload.setText("Unzipping");
          } else {
            progressText.setText((int) mPercent + "%" + " (" + (int) (actualDoneSize / 1024) + "/" + (int) (fileSize / 1024) + " KB)");
          }
        }
      });
      break;

    // unzip
    case UNZIP_PROG_ID:
      // update progress bar display
      mHandler.post(new Runnable() {
        public void run() {
          mProgress.setProgress((int) mPercent);
          if ((int) (mPercent) == 100) {
            btnDownload.setText("Re-Install");
            progressText.setText("Installed");
            btnDownload.setEnabled(true);
            plugInSpinner.setEnabled(true);
            appPref.setValueOf(pluginName, true);
            updateIntallationDisplay(pluginName);
          } else {
            if (btnDownload.getText().toString().equals("Unzipping") == false) {
              btnDownload.setText("Unzipping");
            }
            progressText.setText((int) mPercent + "%" + " (" + (int) (actualDoneSize / 1024) + "/" + (int) (fileSize / 1024) + " KB)");
          }
        }
      });
      break;

    }

  }

}
